package com.intel.factorytest.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.os.SystemProperties;
import android.os.Handler;
import android.os.Message;

import com.intel.factorytest.R;

public class KeyboardAndswitches2 extends BaseActivity  implements OnClickListener{
    
    public static final String TAG = "KeyboardAndswitches2";
    TextView tv,tv2;
    private Button mQuitButton = null;
    boolean walkmankey_toneOnce = true;// FihtdcCode@20110325 WangXuan modify for MUL.B-226
    boolean otherkey_toneOnce = false;// FihtdcCode@20110325 WangXuan add for MUL.B-226
    ToneGenerator mToneGenerator;
    public static final String WALKMAN_KEY_EVENT = "oms.intent.action.CUSTOMER_BUTTON";

    private Button mSuccessBtn = null;
    private Button mFailBtn = null;
    private Button mRepeatBtn = null;
    private TextView mKeyText;    
    private TextView mKeyPassText;
    private StringBuffer resText = new StringBuffer();
    private final static int MSG_GET_KEYCODE_ACTION = 1;
    private static final long TIME_DELAY = 800;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
          Log.i(TAG, "handleMessage msg = " + msg);
          switch (msg.what) {
            case MSG_GET_KEYCODE_ACTION:
                 SystemProperties.set("sys.cit.key.test", "false");
                 finish();
                break;
            default:
                break;
            }
        }
    };
    
    class KeyElement {
        public int mKeyCode;
        public String mKeyName;

        public KeyElement(int key_code, String name)
        {
            mKeyCode = key_code;
            mKeyName = name;
        }        
    }

    private List<KeyElement> mKeyElementList = new ArrayList<KeyElement>();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        Log.i(TAG, "enter onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.keyboardswitches2);    
        initView();
        getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    }

    private void initKeyCheckList()
    {
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_BACK, getResources().getText(R.string.key_back).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_POWER, getResources().getText(R.string.key_power).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_HOME, getResources().getText(R.string.key_home).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_VOLUME_UP, getResources().getText(R.string.key_vol_up).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_VOLUME_DOWN, getResources().getText(R.string.key_vol_down).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_APP_SWITCH, getResources().getText(R.string.key_app_switch).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_CAMERA, getResources().getText(R.string.key_camera).toString() + "\n"));
        //mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_FOCUS, getResources().getText(R.string.key_focus).toString() + "\n")); 

        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_POWER, getResources().getText(R.string.key_power).toString() + "\n"));
        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_VOLUME_UP, getResources().getText(R.string.key_vol_up).toString() + "\n"));
        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_VOLUME_DOWN, getResources().getText(R.string.key_vol_down).toString() + "\n"));
        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_BACK, "Back key"+ "\n"));
        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_HOME, "Home key"+ "\n"));        
        mKeyElementList.add(new KeyElement(KeyEvent.KEYCODE_APP_SWITCH, "Recent key"+ "\n"));
    }

    private void rebuildCheckList()
    {
        mKeyElementList.clear();
        initKeyCheckList();
    }
    
    private void updateText()
    {
        resText.delete(0, resText.length());
        for(KeyElement k: mKeyElementList) {
            resText.append(k.mKeyName);
        }
        mKeyText.setText(resText);        
    }

    private void rmElementWithKeycode(int key_code)
    {
        Iterator<KeyElement> iter = mKeyElementList.iterator();  
        while(iter.hasNext()){  
            KeyElement k = iter.next();  
            if(k.mKeyCode == key_code){  
                iter.remove();  
                break;
            }  
        }        
    }

    private boolean hasElement(int key_code)
    {
        for(KeyElement k: mKeyElementList) {
            if(k.mKeyCode == key_code){  
                return true;
            } 
        }        

        return false;
    }
    
    protected void initView() {
        mKeyText = (TextView)findViewById(R.id.key_text);
        mKeyPassText = (TextView)findViewById(R.id.key_pass_text);
        mSuccessBtn = (Button) findViewById(R.id.success_button);
        mSuccessBtn.setVisibility(View.INVISIBLE);
        mFailBtn = (Button) findViewById(R.id.fail_button);
        mRepeatBtn = (Button) findViewById(R.id.repeat_button);
        rebuildCheckList();
        updateText();        
        attachListener();
    }
    
    private void attachListener() {
        mSuccessBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = true;
                finish();
                SystemProperties.set("sys.cit.key.test", "false");                
            }
        });
        
        attachOnTouchListener(mSuccessBtn);
        
        mFailBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
                SystemProperties.set("sys.cit.key.test", "false");
            }
        });
        
        attachOnTouchListener(mFailBtn);
        
        mRepeatBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                rebuildCheckList();
            }
        });
        
        attachOnTouchListener(mRepeatBtn);
    }    

    public void onClick(View v) {
        finish();
    }
        
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        SystemProperties.set("sys.cit.key.test", "true");        
        IntentFilter filter = new IntentFilter();
        filter.addAction(WALKMAN_KEY_EVENT);
        filter.addAction("com.factorytest.recentkey");
        filter.setPriority(100);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        SystemProperties.set("sys.cit.key.test", "false");        
    }
    
    @Override
    protected void onStop() {
        unregisterReceiver(receiver);
        super.onStop();
    }
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive intent.getAction() = " + intent.getAction());
            if (intent.getAction().compareTo(WALKMAN_KEY_EVENT)==0)
            {
                Log.i(TAG, "onReceive WALKMAN_KEY_EVENT walkmankey_toneOnce = " + walkmankey_toneOnce);
                if (walkmankey_toneOnce)
                {
                    //playTone();
                }
                walkmankey_toneOnce = !walkmankey_toneOnce;
                tv.setText(getString(R.string.SERVICEMENU_WALKMANKEY_TXT));
                this.abortBroadcast();
            } else if ("com.factorytest.recentkey".equals(intent.getAction())) {
                rmElementWithKeycode(KeyEvent.KEYCODE_APP_SWITCH);
                updateText();
                if (isPassed()) {
                    mKeyPassText.setText("PASS");
                    mKeyPassText.setTextColor(Color.GREEN);
                    Message msg = new Message();
                    msg.what = MSG_GET_KEYCODE_ACTION;
                    mHandler.sendMessageDelayed(msg,TIME_DELAY);
                }
            } else {
                Log.i(TAG, "Invalid action");
            }
        }
    };
    
    @Override
    protected void onDestroy()
    {
            SystemProperties.set("sys.cit.key.test", "false");        
            if (mToneGenerator != null) {
                mToneGenerator.release();
                mToneGenerator = null;
            }
//        }
        super.onDestroy();
    }
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event){
        
        Log.i(TAG, "enter dispatchKeyEvent");
        Log.i("hugh-tag", "KeyboardAndswitches2 dispatchKeyEvent event.getAction()=" + event.getAction() + " event.getScanCode()=" + event.getScanCode());

        if (event.getAction() == KeyEvent.ACTION_DOWN){
        
            int pressed_keyCode = event.getKeyCode();
            Log.i(TAG, "pressed_keyCode = " + pressed_keyCode);
            if(KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
               if(!hasElement(KeyEvent.KEYCODE_BACK)) 
                {
                    Log.i(TAG, "enter dispatchKeyEvent >>>> KeyEvent.KEYCODE_BACK  isChecked");
                    super.onBackPressed();
                    return false;
                }
            }

            if (!otherkey_toneOnce)
            {// FihtdcCode@20110325 WangXuan modify for MUL.B-226
                //playTone();
                otherkey_toneOnce = true;
            }
  
            rmElementWithKeycode(pressed_keyCode);
            updateText();
            if (isPassed()) {
                mKeyPassText.setText("PASS");
                mKeyPassText.setTextColor(Color.GREEN);
                Message msg = new Message();
                msg.what = MSG_GET_KEYCODE_ACTION;
                mHandler.sendMessageDelayed(msg,TIME_DELAY);
            }
        }
        else if (event.getAction() == KeyEvent.ACTION_UP)
        {// FihtdcCode@20110325 WangXuan add for MUL.B-226
            otherkey_toneOnce = false;
        }
        return true;
    }    
    
    private boolean isPassed() {
        is_pass = (mKeyElementList.size() == 0);
        return is_pass;
    }


    private void playTone() {
        try {
                mToneGenerator.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT, 150);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mToneGenerator = null;
        }
    }

    @Override
    protected Dialog onCreateDialog(int none){
        return new AlertDialog.Builder(KeyboardAndswitches2.this)
//                    .setIcon(R.drawable.alert_dialog_icon)
                    .setTitle(R.string.SERVICEMENU_DIALOG_TITLE_EXIT_TXT)
                    .setPositiveButton(R.string.SERVICEMENU_OK_TXT, new DialogInterface.OnClickListener() {
                        
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.SERVICEMENU_CANCEL_TXT, new DialogInterface.OnClickListener() {
                        
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    }).create();
    }

    @Override
    public void finish() {
        tc.setTestResult(is_pass);
        super.finish();
    }
    
}

